<?php
namespace Api\Controller;

use Think\Controller;
use Base\FrontController;
use Think\ImageNew;
/**
 * @name 前端造型相关功能提交和查询数据 ，访问本接口下任何方法均要求session中已保留注册用户信息
 * swagger-ui api文档生成cmd： php D:\work\php\swagger-php\vendor\zircote\swagger-php\bin\swagger D:\work\php\wx-third-platform\code\Application\Api\Controller\swagger D:\work\php\wx-third-platform\code\Application\Api\Controller\ApiBHLooksController.class.php  -o D:\work\php\wx-third-platform\code\swui\造型-looks.json
 * @author perry
 *
 */
class ApiBHLooksController extends FrontController
{

    // private $weixin_user;

    function _initialize()
    {
        parent::_initialize();
        
        $this->looksM=D('Home/BHLooks');
        $this->uid=$this->weixin_user['id'];
        $this->imgSaveSubFolder="looks";
    }

    /**
     * @SWG\Get(
     *     path="/ApiBHLooks/getRecommendLooksListByPage",
     *     tags={"getRecommendLooksListByPage"},
     *     description="分页获取百家好推荐造型列表数据",
     *     operationId="getRecommendLooksListByPage",
     * @SWG\Parameter(
     *         name="t",
     *         in="query",
     *         description="分类id,(所有值来自接口/Api/BHLabel/getAll)",
     *         required=false,
     *         type="integer",
     *         format="int32"
     *     ),
     *     @SWG\Parameter(
     *         name="p",
     *         in="query",
     *         description="指定页码(缺省为1)",
     *         required=false,
     *         type="integer",
     *         format="int32"
     *     ),
     *     @SWG\Parameter(
     *         name="ps",
     *         in="query",
     *         description="每页容量(缺省为10)",
     *         required=false,
     *         type="integer",
     *         format="int32"
     *     ),
     *     @SWG\Parameter(
     *         name="name",
     *         in="query",
     *         description="根据名称模糊搜索造型",
     *         required=false,
     *         type="string"
     *         
     *     ),
     *      @SWG\Parameter(
     *         name="id",
     *         in="query",
     *         description="指定唯一id查找一条数据",
     *         required=false,
     *         type="integer",
     *         format="int32"
     *         
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description="上述筛选条件下的每页数据",
     *         @SWG\Schema(
     *             ref="#/definitions/looks"
     *         ),
     *     ),
     *     @SWG\Response(
     *         response="default",
     *         description="接口调用出错",
     *         @SWG\Schema(
     *             ref="#/definitions/ErrorModel"
     *         )
     *     )
     * )
     */
    public function getvaliditybhlabel(){
        $this->user_model = M('bh_kv');
        $re = $this->user_model->where('status =1')->find();
        if($re['img']){
            $re['img']=ic_getUploadImgFullPath('bhlabel',$re['img'],$re['create_time']);
        }else{
            $re['img'] ='';
        }       
        // dump($re);die;
        $this->customReturn(1,$re);
    }
    public function getRecommendLooksListByPage(){
        $type=I('t',1);
        $page=I('p',1);
        $pagesize=I('ps',10);
        $name=I('name',false);
        $id=I('id',-1);
        $status=1;
        //getByPage($uid=0,$type=1,$status=1,$name=false,$page=1,$pageSize=10,$field=true){
        $re=$this->looksM->getByPage(C('super_style_uid'),$type,$status,$name,$page,$pagesize,'id,cate,uid,label,img,item_ids,name,memo,sykh,xykh,pskh,sub_imgs',$id);
        // dump($re);
        $this->customReturn(1,$re);
        
    }

     /**
     * @SWG\Get(
     *     path="/ApiBHLooks/getLooksListByPage",
     *     tags={"getLooksListByPage"},
     *     description="分页获取当前用户的造型列表数据",
     *     operationId="getLooksListByPage",
     *     @SWG\Parameter(
     *         name="p",
     *         in="query",
     *         description="指定页码(缺省为1)",
     *         required=false,
     *         type="integer",
     *         format="int32"
     *     ),
     *     @SWG\Parameter(
     *         name="ps",
     *         in="query",
     *         description="每页容量(缺省为10)",
     *         required=false,
     *         type="integer",
     *         format="int32"
     *     ),
     *     @SWG\Parameter(
     *         name="name",
     *         in="query",
     *         description="根据名称模糊搜索造型",
     *         required=false,
     *         type="string"
     *         
     *     ),
     *      @SWG\Parameter(
     *         name="id",
     *         in="query",
     *         description="指定唯一id查找一条数据",
     *         required=false,
     *         type="integer",
     *         format="int32"
     *         
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description="当前用户上述筛选条件下的每页数据",
     *         @SWG\Schema(
     *             ref="#/definitions/looks"
     *         ),
     *     ),
     *     @SWG\Response(
     *         response="default",
     *         description="接口调用出错",
     *         @SWG\Schema(
     *             ref="#/definitions/ErrorModel"
     *         )
     *     )
     * )
     */
    public function getLooksListByPage(){
        // $type=I('t',1);
        //普通用户的造型没有分类功能 type写死为1 
        $type=1;
        $page=I('p',1);
        $pagesize=I('ps',10);
        $name=I('name',false);
        $id=I('id',-1);
        $status=1;
        //getByPage($uid=0,$type=1,$status=1,$name=false,$page=1,$pageSize=10,$field=true){
        $re=$this->looksM->getByPage($this->uid,$type,$status,$name,$page,$pagesize,'id,cate,uid,label,img,item_ids,name,memo,sykh,xykh,pskh',$id);
        // dump($re);
        $this->customReturn(1,$re);
        
    }

    /**
     * @SWG\Get(
     *     path="/ApiBHLooks/deleteOne",
     *     tags={"BHLooks-deleteOne"},
     *     description="删除当前用户拥有的1条造型数据",
     *     operationId="BHLooks-deleteOne",
     *     produces={"application/json", "application/xml", "text/xml", "text/html"},
     *     @SWG\Parameter(
     *         name="id",
     *         in="query",
     *         description="待删除数据主键id",
     *         required=true,
     *         type="integer",
     *         format="int32"
     *     ),
     *     
     *     @SWG\Response(
     *         response=200,
     *         description="删除成功与否结果",
     *         
     *     ),
     *     @SWG\Response(
     *         response="default",
     *         description="接口调用出错",
     *         @SWG\Schema(
     *             ref="#/definitions/ErrorModel"
     *         )
     *     )
     * )
     */
    public function deleteOne(){
        $id=I('id',-1);
        try {
            $re=$this->looksM->deleteOne($this->uid,$id);
            $this->customReturn(1,$re);
            
        } catch (\Exception $exc) {
            $succ = $exc->getCode() == 1 ? -1 : $exc->getCode();
            $datas = array('errcode' => $succ, 'errmsg' => $exc->getMessage());
            $this->customReturn($succ, $datas);
        }  
    }


    /**
     * @SWG\Get(
     *     path="/ApiBHLooks/addLook",
     *     tags={"BHLooks-addLook"},
     *     description="新增一条造型数据",
     *     operationId="BHLooks-addLook",
     *     produces={"application/json", "application/xml", "text/xml", "text/html"},
     *     @SWG\Parameter(
     *         name="label",
     *         in="query",
     *         description="待新增造型所属子类(百家好灵感造型特有,普通用户造型无需传此参数)",
     *         required=false,
     *         type="integer",
     *         format="int32"
     *     ),
     *     @SWG\Parameter(
     *         name="item_ids",
     *         in="query",
     *         description="待新增造型使用的商品或衣橱id，用半角逗号拼接",
     *         required=true,
     *         type="string"
     *     ), 
     *     @SWG\Parameter(
     *         name="name",
     *         in="query",
     *         description="待新增造型的名称",
     *         required=false,
     *         type="string"
     *     ), 
     *     @SWG\Parameter(
     *         name="memo",
     *         in="query",
     *         description="待新增造型的附注",
     *         required=false,
     *         type="string"
     *     ), 
     *     @SWG\Parameter(
     *         name="look_pic",
     *         in="query",
     *         description="待新增造型的合成图base64编码后字符串",
     *         required=true,
     *         type="string"
     *     ), 
     *     @SWG\Response(
     *         response=200,
     *         description="新增造型结果数组",
     *         @SWG\Schema(
     *             ref="#/definitions/look"
     *         )
     *         
     *     ),
     *     @SWG\Response(
     *         response="default",
     *         description="接口调用出错",
     *         @SWG\Schema(
     *             ref="#/definitions/ErrorModel"
     *         )
     *     )
     * )
     */
    public function addLook(){
        try {
            $newLookData=array();
            $newLookData['create_time']=time();
            $newLookData['update_time']=$newLookData['create_time'];
            //确定造型所属用户
            $newLookData['uid']=$this->uid;
            //确定造型来源
            if(in_array($this->uid, C('super_style_uid'))){
                //是管理员在新增造型，则分类为2管理员的造型灵感
                $newLookData['cate']=2;
            }
            else {
                //普通用户新增造型
                $newLookData['cate']=1;
            }
            //确定造型所属子类(仅管理员造型灵感有子类概念)
            $label=I('label');
            if(ic_isPosInt($label)){
                $newLookData['label']=$label;
            }
            //确定造型的组成元素id
            $item_ids_str=I('item_ids',"");
            $newLookData['item_ids'] = $this->looksM->filterIdStr($item_ids_str);
            //状态默认为启用
            $newLookData['status']=1;
            //确定造型名称
            $newLookData['name']=ic_filterStr(I('name',""));
            //确定造型附注
            $newLookData['memo']=ic_filterStr(I('memo',""));
            //确定上传的造型合成图数据
            //测试base64图像 
            $rePic=I('look_pic');
            //检查上传数据是否为有效图片文件
            $this->checkImgFile($rePic);
            //将base64编码的图片内容还原成jpg图片保存
            // $rePic=str_replace("data:image/jpeg;base64,", "", $rePic);
            // $rePic=substr($rePic, 22);
            $startPos=stripos($rePic, ";base64,");
            if($startPos<=0){
                throw new \Exception("上传图片格式无效(!base64),请重试或联系管理员", -215);
            }
            $rePic=substr($rePic, $startPos+8);
            $rePic=base64_decode($rePic);
            // $this->checkImgFile($rePic); 这里再检查会返回false
            $len=strlen($rePic);
            $serverPath=ic_getUploadImgServerPath('looks',$newLookData['create_time']);
            if(!is_dir($serverPath)) {
                // 检查目录是否编码后的
                if(is_dir(base64_decode($serverPath))) {
                    $serverPath   =   base64_decode($serverPath);
                }else{
                    // 尝试创建目录
                    if(!mkdir($serverPath)){
                        throw new \Exception("保存目录不存在，请联系管理员", -215);
                    }
                }
            }else {
                if(!is_writeable($serverPath)) {
                   throw new \Exception("保存目录不可写，请联系管理员", -333);
                }
            }
            //生成图片文件名
            $saveName=$this->uid."_".ic_micro_time().".png";
            $bytes=file_put_contents($serverPath.$saveName, $rePic);
            if($bytes!=$len){
                throw new \Exception("保存造型合成图失败，请稍候再试".$len, -44);
            }
            //生成m图和s图
            ImageNew::thumb($serverPath.$saveName,$serverPath."s_".$saveName,'',354,395,true);
            ImageNew::thumb($serverPath.$saveName,$serverPath."m_".$saveName,'',708,790,true);
            $newLookData['img']=$saveName;
            //插入数据库
            $newId=$this->looksM->add($newLookData);
            $newLookData['id']=$newId;
            //把图片组装成前端可以直接访问的http全路径
            $newLookData['img']=ic_getUploadImgFullPath('looks',$newLookData['img'],$newLookData['create_time']);
            $this->customReturn(1,$newLookData);
        } catch (\Exception $exc) {
            $succ = $exc->getCode() == 1 ? -1 : $exc->getCode();
            $datas = array('errcode' => $succ, 'errmsg' => $exc->getMessage());
            $this->customReturn($succ, $datas);
        }  
    }

    /**
     * @SWG\Get(
     *     path="/ApiBHLooks/updateLook",
     *     tags={"BHLooks-updateLook"},
     *     description="编辑一条造型数据",
     *     operationId="BHLooks-updateLook",
     *     produces={"application/json", "application/xml", "text/xml", "text/html"},
     *     @SWG\Parameter(
     *         name="id",
     *         in="query",
     *         description="待更新造型主键唯一id",
     *         required=true,
     *         type="integer",
     *         format="int32"
     *     ),
     *     @SWG\Parameter(
     *         name="label",
     *         in="query",
     *         description="待更新造型所属子类(百家好灵感造型特有,普通用户造型无需传此参数)",
     *         required=false,
     *         type="integer",
     *         format="int32"
     *     ),
     *     @SWG\Parameter(
     *         name="item_ids",
     *         in="query",
     *         description="待更新造型使用的商品或衣橱id，用半角逗号拼接",
     *         required=false,
     *         type="string"
     *     ), 
     *     @SWG\Parameter(
     *         name="name",
     *         in="query",
     *         description="待更新造型的名称",
     *         required=false,
     *         type="string"
     *     ), 
     *     @SWG\Parameter(
     *         name="memo",
     *         in="query",
     *         description="待更新造型的附注",
     *         required=false,
     *         type="string"
     *     ), 
     *     @SWG\Parameter(
     *         name="look_pic",
     *         in="query",
     *         description="待更新造型的合成图base64编码后字符串",
     *         required=false,
     *         type="string"
     *     ), 
     *     @SWG\Response(
     *         response=200,
     *         description="更新成功后造型结果数组",
     *         @SWG\Schema(
     *             ref="#/definitions/look"
     *         )
     *         
     *     ),
     *     @SWG\Response(
     *         response="default",
     *         description="接口调用出错",
     *         @SWG\Schema(
     *             ref="#/definitions/ErrorModel"
     *         )
     *     )
     * )
     */
    public function updateLook(){
        try {
            $id=I('id',-1);
            if(!ic_isPosInt($id)){
                throw new \Exception("待更新造型不存在,请检查", -427);  
            }
            $exist=$this->looksM->where("id=".$id)->find();
            if(!$exist){
                throw new \Exception("待更新造型不存在,请刷新页面重试", -431); 
            }
            if($exist['uid']!=$this->uid){
                throw new \Exception("您无权编辑他人的造型，请检查", -431);
            }
            $newLookData=array();
            $newLookData['update_time']=time();
            $newLookData['create_time']=$exist['create_time'];
            //确定造型所属用户
            $newLookData['uid']=$this->uid;
            //确定造型来源
            if(in_array($this->uid, C('super_style_uid'))){
                //是管理员在新增造型，则分类为2管理员的造型灵感
                $newLookData['cate']=2;
            }
            else {
                //普通用户新增造型
                $newLookData['cate']=1;
            }
            //确定造型所属子类(仅管理员造型灵感有子类概念)
            $label=I('label');
            if(ic_isPosInt($label)){
                $newLookData['label']=$label;
            }
            else {
                $newLookData['label']=$exist['label'];
            }
            //确定造型的组成元素id
            $item_ids_str=I('item_ids',"");
            if(ic_checkUnEmpty($item_ids_str)){
                $newLookData['item_ids'] = $this->looksM->filterIdStr($item_ids_str);
            }
            else {
                $newLookData['item_ids']=$exist['item_ids'];
            }
            //编辑时状态不可再更改
            // $newLookData['status']=1;
            //确定造型名称
            $newLookData['name']=ic_filterStr(I('name',""));
            if(!ic_checkUnEmpty($newLookData['name'])){
                $newLookData['name']=$exist['name'];
            }
            //确定造型附注
            $newLookData['memo']=ic_filterStr(I('memo',""));
            if(!ic_checkUnEmpty($newLookData['memo'])){
                $newLookData['memo']=$exist['memo'];
            }
            //确定上传的造型合成图数据
            //测试base64图像 
            $rePic=I('look_pic','');
            if(ic_checkUnEmpty($rePic)){
                //检查上传数据是否为有效图片文件
                $this->checkImgFile($rePic);
                //将base64编码的图片内容还原成jpg图片保存
                // $rePic=str_replace("data:image/jpeg;base64,", "", $rePic);
                // $rePic=substr($rePic, 22);
                $startPos=stripos($rePic, ";base64,");
                if($startPos<=0){
                    throw new \Exception("上传图片格式无效(!base64),请重试或联系管理员", -215);
                }
                $rePic=substr($rePic, $startPos+8);
                $rePic=base64_decode($rePic);
                // $this->checkImgFile($rePic); 这里再检查会返回false
                $len=strlen($rePic);
                $serverPath=ic_getUploadImgServerPath($this->imgSaveSubFolder,$newLookData['create_time']);
                if(!is_dir($serverPath)) {
                    // 检查目录是否编码后的
                    if(is_dir(base64_decode($serverPath))) {
                        $serverPath   =   base64_decode($serverPath);
                    }else{
                        // 尝试创建目录
                        if(!mkdir($serverPath)){
                            throw new \Exception("保存目录不存在，请联系管理员", -215);
                        }
                    }
                }else {
                    if(!is_writeable($serverPath)) {
                       throw new \Exception("保存目录不可写，请联系管理员", -333);
                    }
                }
                //生成图片文件名
                $saveName=$this->uid."_".ic_micro_time().".png";
                $bytes=file_put_contents($serverPath.$saveName, $rePic);
                if($bytes!=$len){
                    throw new \Exception("保存造型合成图失败，请稍候再试".$len, -44);
                }
                //生成m图和s图
                ImageNew::thumb($serverPath.$saveName,$serverPath."s_".$saveName,'',354,395,true);
                ImageNew::thumb($serverPath.$saveName,$serverPath."m_".$saveName,'',708,790,true);
                $newLookData['img']=$saveName;
                //删除老图
                $this->delMulti($serverPath,$exist['img']);
            }
            else {
                $newLookData['img']=$exist['img'];
            }
            //插入数据库
            $row=$this->looksM->where("id=".$id)->save($newLookData);
            $newLookData['id']=$id;
            //把图片组装成前端可以直接访问的http全路径
            $newLookData['img']=ic_getUploadImgFullPath($this->imgSaveSubFolder,$newLookData['img'],$newLookData['create_time']);
            
            $this->customReturn(1,$newLookData);
        } catch (\Exception $exc) {
            $succ = $exc->getCode() == 1 ? -1 : $exc->getCode();
            $datas = array('errcode' => $succ, 'errmsg' => $exc->getMessage());
            $this->customReturn($succ, $datas);
        }  
    }

     private function delMulti($serverPath,$delName){
        @unlink($serverPath.$delName);
        @unlink($serverPath."m_".$delName);
        @unlink($serverPath."s_".$delName);
    }

    private function checkImgFile($img,$ext='jpg'){
        $imginfo = getimagesize($img);
        // dump($imginfo);
        // array(7) {
        //   [0] => int(414)
        //   [1] => int(736)
        //   [2] => int(2)
        //   [3] => string(24) "width="414" height="736""
        //   ["bits"] => int(8)
        //   ["channels"] => int(3)
        //   ["mime"] => string(10) "image/jpeg"
        // }
        if(empty($imginfo) || ($ext == 'gif' && empty($imginfo['bits']))){
            throw new \Exception("上传图片格式无效,请联系管理员", -48);
        }
    }

   

}
